<?php
/**
* Api_Form_Validator_EmailUsed class for Boomeranfg Referral Network
*
* Api_Form_Validator_EmailUsed class contains logical part of the forward mail form. It also
* contain server side validation, filtering and security issues which are handled at server side
*
* Custom validator to check if email address already used or not
* 
* @package      Api_Form_Validator
* @copyright    Copyright (c) 2011-2012 Boomerang Referral Network
* @version      $Id: EmailUsed.php v 1.0.0$
* @since        Class available since Release 1.0.0
* @author       Anindya Roy Chodhury <anindya23@gmail.com>
*/
class Api_Form_Validator_EmailUsed extends Zend_Validate_Abstract
{
    const NOT_MATCH = 'emailUsed';

    /**
     * Entity manager of Doctrine ORM
     * 
     * @var Doctrine\ORM\EntityManager
     */
    private $_em;

    protected $_messageTemplates = array(
        self::NOT_MATCH => 'Email is already used by another user'
    );

    public function __construct()
    {
        $this->_em = Zend_Registry::get('doctrine')->getEntityManager();
    }

    /**
     * Custom Validation method of the form that uses 
     * Api_Form_Validator_EmailUsed validation class
     * 
     * @param integer User Id
     * @return boolean 
     */
    public function isValid($value)
    {
        $value = (string) $value;
        $user = $this->_em->getRepository('Api\Core\Entity\User')
                ->findOneByEmail($value);
        $error = false;

        if (isset($user)) {
            $error = true;
            $this->_error(self::NOT_MATCH);
        }
        return !$error;
    }
}